#include "RR.h"
#include <stdio.h>
#include <stdlib.h>

/**
 * 函数: calculateTimes
 * 功能: 根据时间片轮转调度算法计算每个进程的完成时间、周转时间和等待时间
 *
 * 参数:
 *  - processes: 指向包含多个进程信息的数组
 *  - n: 进程数量
 *  - time_slice: 时间片长度
 *
 * 描述:
 *  计算进程的完成时间，周转时间和等待时间并存在结构体中即可
 */
void
calculateTimes (Process *processes, int n, int time_slice)
{
  int current_time = 0;
  int completed = 0;
  int queue_index = 0;

  while (completed < n) {
      Process *current_process = &processes[queue_index];
      // 若进程未到达，推进时间
      if (current_process->arrival_time > current_time) {
          current_time++;
          continue;
      }
      // 进程运行
      if (current_process->remaining_time <= time_slice) {
          current_time += current_process->remaining_time;
          current_process->remaining_time = 0;
          current_process->completion_time = current_time;
          current_process->turnaround_time = current_process->completion_time - current_process->arrival_time;
          current_process->waiting_time = current_process->turnaround_time - current_process->burst_time;
          completed++;
      } else {
          current_time += time_slice;
          current_process->remaining_time -= time_slice;
      }
      queue_index = (queue_index + 1) % n;
      // 重新定位到未完成且已到达的进程
      while (completed < n && processes[queue_index].remaining_time == 0 && processes[queue_index].arrival_time <= current_time) {
          queue_index = (queue_index + 1) % n;
      }
  }
}
